package win.zxshuo.www.controller.pages;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import win.zxshuo.www.model.BookModel;
import win.zxshuo.www.model.CategoryModel;
import win.zxshuo.www.model.chapters.ChapterModel;
import win.zxshuo.www.service.BookService;
import win.zxshuo.www.service.CategoryService;
import win.zxshuo.www.service.ChapterService;

import java.util.List;

@Controller
@RequestMapping("book")
public class BookController {
    Log logger = LogFactory.getLog(getClass());

    @Autowired
    CategoryService categoryService;

    @Autowired
    ChapterService chapterService;

    @Autowired
    BookService bookService;

    @RequestMapping("/{bookid}/{chapterid}")
    public String getBookChapter(@PathVariable Long bookid, @PathVariable Long chapterid, Model model){
        try {
            BookModel bookModel = bookService.getBookById(bookid);
            ChapterModel chapterModel = chapterService.getBy(bookid,chapterid);
            ChapterModel nextModel = chapterService.getNextChapter(chapterid,bookid);
            ChapterModel previousModel = chapterService.getPreviousChapter(chapterid,bookid);
            // 每个非章节页面都会需要获取的模型
            List<CategoryModel> categoryModels = categoryService.getAllCategories();

            model.addAttribute("book",bookModel);
            model.addAttribute("categories",categoryModels);
            model.addAttribute("chapter",chapterModel);
            model.addAttribute("nextChapter",nextModel);
            model.addAttribute("previousChapter",previousModel);
            return "chapter";
        }catch (Exception e){
            logger.info("读取章节出错");
            logger.error(e.getCause());
        }
        return "";
    }

    @RequestMapping("/{bookid}")
    public String getBookinfo(@PathVariable Long bookid, Model model){
        BookModel bookModel = bookService.getBookById(bookid);
        List<List<ChapterModel>> lists = bookService.getBookChapters(bookid);
        // 每个非章节页面都会需要获取的模型
        List<CategoryModel> categoryModels = categoryService.getAllCategories();
        List<ChapterModel> lastThreeChapters = chapterService.getBookLastThreeChapters(bookModel);

        model.addAttribute("lastThreeChapters",lastThreeChapters);
        ChapterModel firstChapter = lists.get(0).get(0);
        model.addAttribute("categories",categoryModels);
        model.addAttribute("book",bookModel);
        model.addAttribute("chapters",lists);
        model.addAttribute("firstChapter",firstChapter);

        return "book";
    }


}
